package tool;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * @Description:
 * @Author: yjj
 * @Date: 2025/4/29 16:09
 */
public class Main {

    //验证给定的字符串是否符合 "yyyy-MM-dd HH:mm:ss" 格式
    private static final String DATE_TIME_PATTERN = "^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])\\s([01]\\d|2[0-3]):([0-5]\\d):([0-5]\\d)$";
    private static final Pattern pattern = Pattern.compile(DATE_TIME_PATTERN);

    public static void main(String[] args) throws Exception {
        //2025-07-05 08:21:47
        String dateStr = "3753500562834858031";
        System.out.println(parseTime(dateStr));
        JSONObject jsonObject = JSONObject.parseObject(dateStr);
    }

    public static Long parseTime(Object time) {
        try {
            if (Objects.isNull(time)) {
                return new Date().getTime();
            }
            if (StringUtils.isNumeric(time.toString())) {
                return Long.parseLong(time.toString());
            } else if (isValidDateTime(time.toString())) {//yyyy-MM-dd HH:mm:ss
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                // 解析字符串为 LocalDateTime
                LocalDateTime localDateTime = LocalDateTime.parse(time.toString(), formatter);
                // 转换为 Date（注意时区）
                Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
                return date.getTime();
            } else {//最原始的方式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXX");
                OffsetDateTime odt = OffsetDateTime.parse(time.toString(), formatter);
                return odt.toInstant().toEpochMilli();
            }
        } catch (Exception e) {
            System.out.println("error: " + e.getMessage());
            return new Date().getTime();
        }
    }

    /**
     * 验证给定的字符串是否符合 "yyyy-MM-dd HH:mm:ss" 格式
     */
    public static boolean isValidDateTime(String dateTimeStr) {
        if (dateTimeStr == null) {
            return false;
        }
        Matcher matcher = pattern.matcher(dateTimeStr);
        return matcher.matches();
    }
}
